package com.example.demo.story.impl;

import com.example.demo.story.NetStoryServiceAbstract;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.Iterator;

/**
 * @Author TCJ
 * @create 2024/1/26
 */
public class MhtImpl extends NetStoryServiceAbstract {
    @Override
    public String getBaseUrl() {
        return "http://www.mhtxs.cc";
    }

    @Override
    public String getReadUrl() {
        return getBaseUrl()+"/185/185859/";
    }

    @Override
    public void analysisChapter() {
        Document html = super.getHtml(getReadUrl());
        Elements elements = html.body().getElementsByClass("novel_list");
        super.dto.setTitle("changsheng---");
        if (elements.size() > 1){
            throw new RuntimeException("错误");
        }
        Element list = elements.get(0);
        assert list != null;
        Elements dd = list.getElementsByTag("dd");
        for (Element element : dd) {
                Elements a = element.getElementsByTag("a");
                super.dto.getChapter().put(a.text(), getReadUrl() +  a.attr("href"));
        }

    }

    @Override
    public String getContent(String url) {
        StringBuilder sb = new StringBuilder();
        Document html = super.getHtml(url);
        if (html == null) {
            System.err.println("No document found for url " + url);
            return "没找到该文章！";
        }
        Element content = html.body().getElementsByClass("content").get(0);
        assert content != null;
        Elements children = content.children();
        Iterator<Element> iterator = children.iterator();
        while (iterator.hasNext()) {
            Element element = iterator.next();
            if ("p".equals(element.tag().getName()) || "div".equals(element.tag().getName())){
                iterator.remove();
            }
        }

        return sb.append(content.text()).toString();
    }
}
